#include "stdafx.h"
#include "Client.h"
	
enum GameMessages
{
	    SPAWN_POSITION=ID_USER_PACKET_ENUM+1,
	    POSITION_UPDATE=ID_USER_PACKET_ENUM+2
};

void Client::createClient(char *maxNumPlayers){
	client = RakNet::RakPeerInterface::GetInstance();

	maxPlayers = maxNumPlayers;
	client -> Startup(atoi(maxPlayers), &RakNet::SocketDescriptor(), 1);
}

void Client::connect(char* ip, char* port, const char* password) {
	//client -> Connect(ip, atoi(port), password, strlen(password));

	RakNet::ConnectionAttemptResult res = client->Connect(ip, atoi(port), password, strlen(password));
	RakAssert(res == RakNet::CONNECTION_ATTEMPT_STARTED);
	
	connected = false;
}

void Client::receivePackets() {
	for (packet=client->Receive();
			packet;
			client->DeallocatePacket(packet), packet=client->Receive())
	{
		RakNet::BitStream bsIn(packet->data,packet->length,false);
		bsIn.IgnoreBytes(sizeof(RakNet::MessageID));
		bsIn.Read(int_message);
	
		switch (packet->data[0])
		{
		case SPAWN_POSITION:
			std::cout << "I am player #" << int_message << std::endl;
			break;
		case ID_CONNECTION_REQUEST_ACCEPTED:
			connected = true;
			break;
		case POSITION_UPDATE:
			// received new position of other player from server
			std::cout << "Recieved a position from other player! " << int_message << std::endl;
			break;
		default:
			printf("New Message, %i has arrived.\n", packet->data[0]);
			break;
		}
		bsOut.Reset();
	}
}

void Client::disconnect() {
	RakNet::RakPeerInterface::DestroyInstance(client);
}